import { uniModal } from "../utils/uniPromise";
import { mapActions } from "vuex";
import {
  alipay,
  wxPay,
  yinlianPay,
  huanxunPay,
  baiduPay,
  TTPay,
} from "../utils/weixinPay";

export const payOrder = {
  data() {
    return {
      payStatus: false,
      templateIds: [],
    };
  },
  mounted() {
    // #ifdef MP-WEIXIN
    this.getTemplateId();
    // #endif
  },
  methods: {
    ...mapActions(["loadUserCount"]),
    // 获取职工信息
    GetMeetingUsers() {
      return new Promise((resolve, reject) => {
        if (this.vuex_business.pk_id == 1007) {
          this.$loading();
          this.$resPost("GetMeetingUsers")
            .then((res) => {
              if (!res.data.pk_id) {
                uni.showToast({
                  title: "请先绑定职工信息",
                  icon: "none",
                });
                setTimeout(() => {
                  reject();
                }, 1000);
                return;
              }
              this.$hide();
              resolve();
            })
            .catch((err) => {
              this.$hide();
              reject(false);
            });
          return;
        }
        resolve();
      });
    },
    /**
     * params 提交订单参数
     * options 其他辅助判断参数
     * */
    _submitOrder(params, options = {}) {
      if (!this.vuex_business.appid) {
        this.$toast("无商家信息，请刷新应用");
        return;
      }
      if (this.payStatus) return;
      let defaultOptions = {
        prodName: this.vuex_business.name,
        totalPrice: 0,
        pay_type: "1",
        order_type: 1,
        orderApi: "AddOrderProduct",
        updateApi: "UpdateOrderStatus",
        creatPayApi: "GetCreateOrderPay",
        redirectUrl: "/package/order/list/index",
        tipName: "支付",
        tipContent: "是否支付订单",
        modal: true,
        remark: "商品订单",
        router: "redirectTo",
        integral: false,
        createAble: true,
        delayed: false,
        payErr: true,
        parameter_obj: {},
      };
      options = {
        ...defaultOptions,
        ...options,
      };
      return new Promise((resolve, reject) => {
        this.GetMeetingUsers()
          .then(() => {
            this.setSubMsg()
              .then(() => {
                if (options.modal) {
                  uniModal({
                    title: options.tipName,
                    content: options.tipContent,
                  })
                    .then(() => {
                      if (options.createAble) {
                        this.createOrder(params, options);
                      }
                      resolve(options);
                    })
                    .catch(() => {
                      this.payStatus = false;
                      reject();
                    });
                } else {
                  if (options.createAble) {
                    this.createOrder(params, options);
                  }
                  resolve(options);
                }
              })
              .catch(() => {
                reject();
              });
          })
          .catch(() => {
            this.payStatus = false;
            reject();
            this.$to("/package/user/user-members/index");
          });
      });
    },

    createOrder(params, opts) {
      // #ifdef APP-PLUS
      if (opts.pay_type == "7") {
        params.business_appid = this.vuex_businessObj.alipayappid;
      } else {
        params.business_appid = this.vuex_business.appid;
      }
      // #endif
      // #ifndef APP-PLUS
      params.business_appid = this.vuex_business.appid;
      // #endif
      this.$loading();

      return new Promise((resolve, reject) => {
        let time = 0;
        if (opts.delayed) {
          time = parseInt(Math.random() * 4000);
        }
        let json_detailed = params.json_detailed;
        setTimeout(() => {
          delete params.json_detailed;
          this.onAddOrderSuccess()
            .then(() => {
              this.$resPost(opts.orderApi, params, json_detailed)
                .then(({ data }) => {
                  this.createFinishSuccess(data.order_no);
                  if (opts.totalPrice <= 0) {
                    this.updateOrder(data.order_no, opts)
                      .then(() => {
                        this.$hide();
                        this.onOrderUptateSuccess(data);
                        resolve(data);
                        if (opts.redirectUrl) {
                          this.$linkTo(opts.redirectUrl, opts.router);
                        }
                      })
                      .catch(() => {
                        reject();
                        if (opts.redirectUrl) {
                          setTimeout(() => {
                            this.$linkTo(opts.redirectUrl, opts.router);
                          }, 1000);
                        }
                      });
                  } else {
                    if (params.coupon_id > 0 && opts.pay_type == "6") {
                      opts.pay_type = "1";
                    }
                    let datas = {
                      ...data,
                      bill_type: params.bill_type,
                    };
                    this.judgeTypeToPay(data, opts)
                      .then(() => {
                        this.$hide();
                        this.onOrderUptateSuccess(data);
                        resolve(data);
                        if (opts.redirectUrl) {
                          this.$linkTo(opts.redirectUrl, opts.router);
                        }
                      })
                      .catch((err) => {
                        this.$hide();
                        reject(data.pk_id);
                        if (err) {
                          this.$toast({
                            title: err,
                          });
                        }
                        if (opts.redirectUrl && opts.payErr) {
                          setTimeout(() => {
                            this.$linkTo(opts.redirectUrl, opts.router);
                          }, 1000);
                        }
                      });
                  }
                })
                .catch((res) => {
                  this.$hide();
                  reject();
                });
            })
            .catch((res) => {
              this.$hide();
              reject();
            });
        }, time);
      });
    },
    judgeTypeToPay(params, opts) {
      return new Promise((resolve, reject) => {
        if (opts.totalPrice <= 0) {
          this.updateOrder(params.order_no, opts)
            .then(() => {
              resolve();
            })
            .catch(() => {
              reject();
            });
          return;
        }
        if (opts.pay_type == "1") {
          wxPay({
            bill_type: params.bill_type,
            prodName: opts.prodName,
            order_no: params.order_no,
            total_fee: opts.totalPrice,
            createPayApi: opts.creatPayApi,
            parameter_obj: opts.parameter_obj,
          })
            .then(() => {
              this.updateOrder(params.order_no, opts)
                .then(() => {
                  resolve();
                })
                .catch(() => {
                  reject();
                });
            })
            .catch((err) => {
              reject(err);
            });
        } else if (opts.pay_type == "6") {
          if (opts.payApi == 2) {
            yinlianPay({
              order_no: params.order_no,
              total_fee: opts.totalPrice,
            })
              .then(() => {
                this.updateOrder(params.order_no, opts)
                  .then(() => {
                    resolve();
                  })
                  .catch(() => {
                    reject();
                  });
              })
              .catch(() => {
                reject();
              });
          } else {
            huanxunPay({
              prodName: opts.prodName,
              order_no: params.order_no,
              total_fee: opts.totalPrice,
            })
              .then(() => {
                this.updateOrder(params.order_no, opts)
                  .then(() => {
                    resolve();
                  })
                  .catch(() => {
                    reject();
                  });
              })
              .catch((err) => {
                reject(err);
              });
          }
        } else if (opts.pay_type == "2") {
          this.loadUserCount()
            .then((userCount) => {
              if (
                parseFloat(userCount.balance) >= parseFloat(opts.totalPrice)
              ) {
                this._payByBalance(params, opts)
                  .then(() => {
                    this.updateOrder(params.order_no, opts)
                      .then(() => {
                        resolve();
                      })
                      .catch(() => {
                        reject();
                      });
                  })
                  .catch(() => {
                    reject();
                  });
              } else {
                reject("余额不足");
              }
            })
            .catch(() => {
              reject();
            });
        } else if (opts.pay_type == "7") {
          let obj = {
            prodName: opts.prodName,
            order_no: params.order_no,
            total_fee: opts.totalPrice,
          };
          alipay(obj, opts)
            .then(() => {
              this.updateOrder(params.order_no, opts)
                .then(() => {
                  resolve();
                })
                .catch(() => {
                  reject();
                });
            })
            .catch((err) => {
              reject(err);
            });
        } else if (opts.pay_type == "8") {
          baiduPay({
            prodName: opts.prodName,
            order_no: params.order_no,
            total_fee: opts.totalPrice,
          })
            .then(() => {
              this.updateOrder(params.order_no, opts)
                .then(() => {
                  resolve();
                })
                .catch((err) => {
                  reject();
                });
            })
            .catch((err) => {
              reject(err);
            });
        } else if (opts.pay_type == "9") {
          TTPay({
            prodName: opts.prodName,
            order_no: params.order_no,
            total_fee: opts.totalPrice,
          })
            .then(() => {
              this.updateOrder(params.order_no, opts)
                .then(() => {
                  resolve();
                })
                .catch((err) => {
                  reject();
                });
            })
            .catch((err) => {
              reject();
            });
        } else {
          reject("无匹配的支付方式");
        }
      });
    },
    _payByBalance(params, opts) {
      return this.$resPost("AddUsersConsume", {
        order_id: params.pk_id,
        order_no: params.order_no,
        trade_no: "",
        type: 1,
        pay_type: 2,
        amount: opts.totalPrice,
        order_type: opts.order_type,
        status: 1,
        remark: opts.remark || "商品订单",
      });
    },
    updateOrder(order_no, opts) {
      if (!opts.updateApi) {
        return new Promise((resolve, reject) => {
          resolve();
        });
      }
      if (opts.integral) {
        opts.pay_type = opts.pay_type == 1 ? 5 : 4;
        if (opts.totalPrice <= 0) {
          opts.pay_type = 5;
        }
      } else if (opts.totalPrice <= 0) {
        opts.pay_type = opts.pay_type != 3 ? 0 : opts.pay_type;
      }
      return this.$resPost(
        opts.updateApi,
        {
          order_no: order_no,
          type: opts.pay_type,
          ...(opts.updateParams || {}),
        },
        {},
        {
          timeout: "请求超时，请联系客服",
        }
      );
    },

    onAddOrderSuccess() {
      return new Promise((resolve, reject) => {
        if (this.onAddOrderPay && typeof this.onAddOrderPay == "function") {
          return this.onAddOrderPay()
            .then((res) => {
              resolve();
            })
            .catch(() => {
              reject();
            });
        } else {
          resolve();
        }
      });
    },

    createFinishSuccess(order) {
      if (
        this.createProductOrder &&
        typeof this.createProductOrder == "function"
      ) {
        this.createProductOrder(order);
      }
    },

    onOrderUptateSuccess() {
      if (
        this.onWriteOffExchange &&
        typeof this.onWriteOffExchange == "function"
      ) {
        this.onWriteOffExchange();
      }
    },

    setSubMsg() {
      return new Promise((resolve, reject) => {
        if (this.templateIds.length < 1) {
          resolve();
          return;
        }
        // #ifdef MP-WEIXIN
        this.$loading();
        uni.getSetting({
          withSubscriptions: true,
          success: (res) => {
            let bol = false;
            if (!res.subscriptionsSetting.itemSettings) {
              bol = true;
            } else if (res.subscriptionsSetting.itemSettings) {
              bol = this.templateIds.some((template_id) => {
                if (
                  res.subscriptionsSetting.itemSettings[template_id] !==
                  "accept"
                ) {
                  bol = false;
                  return true;
                } else {
                  return false;
                }
              });
            }
            if (bol) {
              setTimeout(() => {
                this.$hide();
              }, 500);
              uni.requestSubscribeMessage({
                tmplIds: this.templateIds,
                success: (res1) => {
                  resolve();
                },
                fail: (err) => {
                  console.log("订阅申请失败", err);
                  resolve();
                },
              });
            } else {
              this.$hide();
              resolve();
            }
          },
        });
        // #endif
      });
    },
    getTemplateId() {
      // #ifdef MP-WEIXIN
      this.$resPost("GetSubscribeLibrary", {
        type: "1,2,3",
      }).then(({ data }) => {
        this.templateIds = data.map((item) => {
          return item.template_id;
        });
      });
      // #endif
    },
  },
};
